package com.kefu.chat.controller;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kefu.chat.model.ChatLeaveMsg;
import com.kefu.chat.service.ChatLeaveMsgService;
import com.kefu.chat.vo.ChatLeaveMsgSearchVo;
import com.kefu.chat.vo.ChatLeaveMsgUpdateVo;
import com.kefu.common.annotation.Permission;
import com.kefu.common.context.KefuContext;
import com.kefu.common.controller.AbstractBaseController;
import com.kefu.common.result.Result;
import com.kefu.common.result.ResultGenerator;
import com.kefu.common.vo.DeleteVo;
import com.kefu.sys.mapper.SysUserMapper;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags = "在线留言")
@RestController
@RequestMapping("chat/leaveMsg")
public class ChatLeaveMsgController extends AbstractBaseController {

    @Autowired
    private ChatLeaveMsgService chatLeaveMsgService;
    @Autowired
    SysUserMapper sysUserMapper;

    @PostMapping("/update")
    @ApiOperation(value = "修改留言")
    public Result<String> update(@Validated @RequestBody ChatLeaveMsgUpdateVo chatLeaveMsgVo) {
        logger.info("修改留言:{}", chatLeaveMsgVo);

        ChatLeaveMsg info = chatLeaveMsgVo.convert();
        chatLeaveMsgService.update(info);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/delete")
    @ApiOperation(value = "删除在线留言", notes = "删除在线留言")
    public Result<String> delete(@Validated @RequestBody DeleteVo delete) {
        logger.info("删除在线留言:{}", delete);

        chatLeaveMsgService.deleteById(delete.getId());
        return ResultGenerator.genSuccessResult();
    }


    @PostMapping("/list")
    @ApiOperation(value = "查询在线留言", notes = "查询在线留言")
    public Result<Page<ChatLeaveMsg>> list(@Validated @RequestBody ChatLeaveMsgSearchVo search) {

        Page<ChatLeaveMsg> page = chatLeaveMsgService.search(search);
        Map<String, String> userMap = sysUserMapper.getUserNameMap(KefuContext.getKefuContext().getTenantId());
        page.getRecords().forEach(item -> item.setUpdateUserName(userMap.get(item.getUpdateUser())));
        return ResultGenerator.genSuccessResult(page);
    }
}
